<template>
  <div class="course-container">
    <van-nav-bar title="课程管理" left-arrow @click-left="$router.back()" />
    
    <div class="course-content">
      <!-- 搜索栏 -->
      <van-search 
        v-model="searchValue" 
        placeholder="搜索课程名称"
        @search="onSearch"
        @clear="onClear"
      />
      
      <!-- 添加按钮 -->
      <van-button 
        type="primary" 
        block 
        class="add-btn"
        @click="showAddDialog = true"
      >
        <van-icon name="plus" /> 添加课程
      </van-button>
      
      <!-- 课程列表 -->
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-card
          v-for="item in courseList"
          :key="item.id"
          :title="item.name"
          :desc="`课程代码: ${item.code} | 学分: ${item.credits} | 课时: ${item.hours}小时`"
        >
          <template #tags>
            <van-tag :type="item.type === 'required' ? 'primary' : 'success'">
              {{ item.type === 'required' ? '必修' : '选修' }}
            </van-tag>
            <van-tag type="warning">{{ item.department }}</van-tag>
          </template>
          <template #footer>
            <van-button size="mini" @click="editCourse(item)">编辑</van-button>
            <van-button size="mini" type="danger" @click="deleteCourse(item)">删除</van-button>
          </template>
        </van-card>
      </van-list>
    </div>
    
    <!-- 添加/编辑弹窗 -->
    <van-popup 
      v-model:show="showAddDialog" 
      position="bottom" 
      :style="{ height: '70%' }"
      round
      closeable
    >
      <div class="form-container">
        <h3>{{ editingCourse ? '编辑课程' : '添加课程' }}</h3>
        <van-form @submit="onSubmit">
          <van-field
            v-model="formData.name"
            name="name"
            label="课程名称"
            placeholder="请输入课程名称"
            :rules="[{ required: true, message: '请输入课程名称' }]"
          />
          <van-field
            v-model="formData.code"
            name="code"
            label="课程代码"
            placeholder="请输入课程代码"
            :rules="[{ required: true, message: '请输入课程代码' }]"
          />
          <van-field
            v-model="formData.credits"
            name="credits"
            label="学分"
            type="number"
            placeholder="请输入学分"
            :rules="[{ required: true, message: '请输入学分' }]"
          />
          <van-field
            v-model="formData.hours"
            name="hours"
            label="课时"
            type="number"
            placeholder="请输入课时"
            :rules="[{ required: true, message: '请输入课时' }]"
          />
          <van-field
            v-model="formData.department"
            name="department"
            label="开课院系"
            placeholder="请输入开课院系"
            :rules="[{ required: true, message: '请输入开课院系' }]"
          />
          <van-field name="type" label="课程类型">
            <template #input>
              <van-radio-group v-model="formData.type" direction="horizontal">
                <van-radio name="required">必修</van-radio>
                <van-radio name="elective">选修</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-model="formData.description"
            name="description"
            label="课程描述"
            type="textarea"
            placeholder="请输入课程描述"
            rows="3"
          />
          <div class="form-buttons">
            <van-button block type="primary" native-type="submit">
              {{ editingCourse ? '更新' : '添加' }}
            </van-button>
          </div>
        </van-form>
      </div>
    </van-popup>
    
    <van-tabbar v-model="activeTab" fixed>
      <van-tabbar-item icon="wap-home-o" to="/dashboard">首页</van-tabbar-item>
      <van-tabbar-item icon="calendar-o" to="/calendar">日历</van-tabbar-item>
      <van-tabbar-item icon="orders-o" to="/schedule">排课</van-tabbar-item>
      <van-tabbar-item icon="manager-o" to="/master/teacher">管理</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'

const searchValue = ref('')
const loading = ref(false)
const finished = ref(false)
const courseList = ref([])
const showAddDialog = ref(false)
const editingCourse = ref(null)
const activeTab = ref(3)

const formData = ref({
  name: '',
  code: '',
  credits: '',
  hours: '',
  department: '',
  type: 'required',
  description: ''
})

const onLoad = async () => {
  try {
    // 模拟加载数据
    setTimeout(() => {
      if (courseList.value.length === 0) {
        courseList.value = [
          { 
            id: 1, 
            name: '高等数学', 
            code: 'MATH001', 
            credits: 4, 
            hours: 64, 
            department: '数学系', 
            type: 'required',
            description: '数学基础课程'
          },
          { 
            id: 2, 
            name: '数据结构', 
            code: 'CS002', 
            credits: 3, 
            hours: 48, 
            department: '计算机系', 
            type: 'required',
            description: '计算机专业核心课程'
          },
          { 
            id: 3, 
            name: '人工智能导论', 
            code: 'CS101', 
            credits: 2, 
            hours: 32, 
            department: '计算机系', 
            type: 'elective',
            description: 'AI基础理论课程'
          }
        ]
      }
      loading.value = false
      finished.value = true
    }, 1000)
  } catch (error) {
    showToast('加载失败')
    loading.value = false
  }
}

const onSearch = (value) => {
  // 实现搜索逻辑
  console.log('搜索:', value)
}

const onClear = () => {
  searchValue.value = ''
}

const editCourse = (item) => {
  editingCourse.value = item
  formData.value = { ...item }
  showAddDialog.value = true
}

const deleteCourse = async (item) => {
  try {
    await showConfirmDialog({
      title: '确认删除',
      message: `确定要删除课程"${item.name}"吗？`,
    })
    
    // 这里应该调用删除API
    const index = courseList.value.findIndex(c => c.id === item.id)
    if (index > -1) {
      courseList.value.splice(index, 1)
      showToast('删除成功')
    }
  } catch {
    // 用户取消
  }
}

const onSubmit = async () => {
  try {
    if (editingCourse.value) {
      // 编辑
      const index = courseList.value.findIndex(c => c.id === editingCourse.value.id)
      if (index > -1) {
        courseList.value[index] = { 
          ...editingCourse.value, 
          ...formData.value,
          credits: parseInt(formData.value.credits),
          hours: parseInt(formData.value.hours)
        }
      }
      showToast('更新成功')
    } else {
      // 添加
      const newCourse = {
        id: Date.now(),
        ...formData.value,
        credits: parseInt(formData.value.credits),
        hours: parseInt(formData.value.hours)
      }
      courseList.value.unshift(newCourse)
      showToast('添加成功')
    }
    
    showAddDialog.value = false
    resetForm()
  } catch (error) {
    showToast('操作失败')
  }
}

const resetForm = () => {
  formData.value = {
    name: '',
    code: '',
    credits: '',
    hours: '',
    department: '',
    type: 'required',
    description: ''
  }
  editingCourse.value = null
}

onMounted(() => {
  onLoad()
})
</script>

<style lang="scss" scoped>
.course-container {
  padding-bottom: 50px;
}

.course-content {
  padding: $padding-md;
}

.add-btn {
  margin: $padding-md 0;
  
  .van-icon {
    margin-right: 4px;
  }
}

.van-card {
  margin-bottom: $padding-sm;
  border-radius: $border-radius-md;
  overflow: hidden;
  
  :deep(.van-card__footer) {
    display: flex;
    gap: $padding-xs;
  }
  
  :deep(.van-card__header) {
    .van-tag {
      margin-right: $padding-xs;
    }
  }
}

.form-container {
  padding: $padding-lg;
  
  h3 {
    text-align: center;
    margin-bottom: $padding-lg;
    color: $text-color;
  }
}

.form-buttons {
  margin-top: $padding-lg;
}
</style>